import React, {Component} from 'react';
import { Card, Button,Table, message, Modal, Input, Form } from 'antd';
import {PlusOutlined} from "@ant-design/icons";
import {reqCategoryList,reqAddCategory,reqUpdateCategory} from '../../api/index.js'
import {paginationSize} from '../../config/index.js'

class Category extends Component {
  state = {
    categoryList: [],
    isLoading: true,
    visible: false,   // 显示模态对话框
    modelType: '',  // 模态对话框类型，添加add，修改update
    modelCurrentValue: '',  // 模态对话框中的值
    modelCurrentId: '',  //修改分类名称时，点击的分类名称id
  };
  formRef = React.createRef();
  render() {
    let {categoryList,isLoading,visible,modelType,modelCurrentValue} = this.state;
    let dataSource = categoryList
    const columns = [
      {title:'分类名称',dataIndex:'name',key:'_id'},
      {title:'操作',width: '30%',align:'center',
        render: (value)=><Button type='link' onClick={this.showUpdateModal.bind(this,value)}>修改分类</Button>
      },
    ];
    return <div>
      {/* card */}
      <Card extra={<Button onClick={this.showAddModal} type="primary" icon={<PlusOutlined/>}>添加</Button>}>
        {/* table表格 */}
        <Table
          dataSource={dataSource}
          columns={columns}
          bordered
          rowKey="_id"
          loading={isLoading}
          pagination={{pageSize: paginationSize,showQuickJumper:true}}
        />
      </Card>
      {/* 模态对话框，点击出现 */}
      <Modal
        title={modelType === 'add' ? '添加分类' : '修改分类'}
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
      >
        <Form
          ref={this.formRef}
        >
          <Form.Item
            name="categoryName"
            rules={[{ required: true, message: '分类名称必须输入！' }]}
            initialValue = {modelCurrentValue}
          >
            <Input placeholder="请输入分类名称"/>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  }
  
  componentDidMount() {
    // 调用获取商品分类列表
    this.getCategoryList()
  }
  
  // 显示添加模态对话框
  showAddModal = () => {
    this.setState({
      visible: true,
      modelType: 'add'
    })
    // 使用 setFieldsValue 来动态清空表单值
    if (this.formRef.current){
      this.formRef.current.setFieldsValue({
        categoryName: ''
      })
    }
  };
  
  // 显示修改模态对话框
  showUpdateModal = (value) => {
    this.setState({
      visible: true,
      modelType: 'update',
      modelCurrentId: value._id,
      modelCurrentValue: value.name
    });
    // 表单值必须使用 setFieldsValue 来动态改变
    if (this.formRef.current){
      this.formRef.current.setFieldsValue({
        categoryName: value.name
      })
    }
  };
  
  // 新增分类列表
  toAdd = async (values) => {
    // 向后台添加数据
    let res = await reqAddCategory(values.categoryName)
    let { status, data, msg } = res
    if (status === 0) {  // 向后台提交数据成功
      let categoryList = [...this.state.categoryList]
      // 将获取的值添加到状态categoryList里
      categoryList.unshift(data)
      // 重新设置状态
      this.setState({
        categoryList
      })
      // 提示
      message.success('添加分类成功',1)
      
      this.setState({
        visible: false,   //隐藏弹窗
        modelCurrentValue: '',  // 模态对话框中的值清零
        modelCurrentId: '',  //分类名称id清零
      })
      this.formRef.current.resetFields();  //清空表单
    } else {  //向后台提交数据失败
      message.error(msg, 1)
    }
  }
  
  // 修改分类列表
  toUpdate = async (values) => {
    let {modelCurrentId} = this.state;
    let categoryValue = values.categoryName
    let res = await reqUpdateCategory({categoryId:modelCurrentId, categoryName:categoryValue});
    let {status, msg} = res
    if (status === 0) {
      // 调用获取商品分类列表,刷新页面
      this.getCategoryList();
      message.success('修改成功!')
  
      this.setState({
        visible: false,   //隐藏弹窗
        modelCurrentValue: '',  // 模态对话框中的值清零
        modelCurrentId: '',  //分类名称id清零
      })
      this.formRef.current.resetFields();  //清空表单
    } else {
      message.warning(msg, 1)
    }
  }
  
  // 点击模态对话框ok
  handleOk = async() => {
    let {modelType} = this.state
  
    // 验证表单是否通过
    this.formRef.current.validateFields()
      .then(async values => {  // 验证通过
        if (modelType==='add'){  //添加
          if (modelType === 'add') this.toAdd(values)
        } else {  //修改更新
          if (modelType === 'update') this.toUpdate(values)
        }
      })
      .catch(errorInfo => {   //验证未通过
        message.warning(errorInfo.errorFields[0].errors[0],1)
      });
  };
  
  // 点击模态对话框取消
  handleCancel = () => {
    this.setState({
      visible: false,   //隐藏弹窗
      modelCurrentValue: '',  // 模态对话框中的值清零
      modelCurrentId: '',  //分类名称id清零
    });
    this.formRef.current.resetFields();  //清空表单
  };
  
  // 获取商品分类列表
  getCategoryList = async () => {
    let res = await reqCategoryList()
    let {status, data, msg} = res
    if (status === 0) {
      this.setState({
        categoryList:data.reverse(),
        isLoading: false
      })
    } else {
      message.warning(msg, 1)
    }
  }
}

export default Category;
